package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.*;
import org.springframework.context.annotation.Scope;
import com.example.onlinemonitoring.serviceImpl.ScsensorServiceImpl;
import com.example.onlinemonitoring.serviceImpl.ScbussensorServiceImpl;
import com.example.onlinemonitoring.serviceImpl.SclinesensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.text.ParseException;

/**
 * 小电流选线
 */
@Service("scCom")
@Scope("prototype")
public class ScCom extends CommPortManager {
    @Autowired
    private ScsensorServiceImpl scserviceimpl;
    @Autowired
    private SclinesensorServiceImpl sclineserviceimpl;
    @Autowired
    private ScbussensorServiceImpl scbusserviceimpl;
    // 遥信数据
    private static String telecommandState = "遥信";
    private static long telecommandTime = 0;
    // 遥测数据
    private static String telemetryState = "遥测";
    private static long telemetryTime = 0;
    @Value("${ScConfig.expirationTime}")
    private long expirationTime;
    long lastrecvtime = new Date().getTime();

    @Override
    public void receiveData(String str) {
        lastrecvtime = new Date().getTime();
        str.toUpperCase();
        setText(str);
        Date dt = new Date();
        if ("EB90EB90EB90".equals(str.substring(0, 12))) {
            buffer = str;
        } else {
            buffer += str;
        }
        if (buffer.length() < 18) {
            setText("数据长度过短，已加入接收缓冲区");
            return;
        }
        if (!(buffer.length() == (parseHex4(buffer.substring(16, 18)) * 12 + 12 * 2))) {
            setText("数据不完整，已加入接收缓冲区");
            return;
        }

        // 遥信(让数据在指定时间内才进行逻辑计算)
        if ("F4".equals(buffer.substring(14, 16))) {
            // 如果当前时间大于下次处理数据时间,则进入
            if (System.currentTimeMillis() > telecommandTime) {
                synchronized (telecommandState) {
                    if (System.currentTimeMillis() > telecommandTime) {
                        byte[] carr = HexUtil.hexString2Bytes(buffer);
                        if ((carr[7] & 0xFF) == 0xF4)// yaoxin
                        {
                            setText("==============正在解析遥信数据==============");
                            for (int i = 1; i <= 4; i++) {
                                int grdalm = carr[12 + i] >> 0 & 0x1;
                                int resonantalm = carr[12 + i] >> 1 & 0x1;
                                int picklnstart = carr[12 + i] >> 2 & 0x1;
                                int busbartwj = carr[12 + i] >> 3 & 0x1;
                                int aphasegrd = carr[12 + i] >> 4 & 0x1;
                                int bphasegrd = carr[12 + i] >> 5 & 0x1;
                                int cphasegrd = carr[12 + i] >> 6 & 0x1;
                                int allreturn = carr[12 + i] >> 7 & 0x1;
                                int k = 2 * i - 2;
                                int k1 = k - 1;
                                int reasonofrdcut = 0, resultofrdcut = 0, statusofpacc = 0, resultofpacc = 0,
                                        resultofselln = 0;
                                int busbarovhl = carr[81] >> (i - 1) & 0x1;
                                // 轮切原因
                                if ((carr[63] >> k & 0x1) == 0 && (carr[63] >> k1 & 0x1) == 0) {
                                    // 不写入轮切原因
                                } else if ((carr[63] >> k & 0x1) == 1 && (carr[63] >> k1 & 0x1) == 0) {
                                    // 选线错误轮切
                                    reasonofrdcut = 1;
                                } else {
                                    // 长时限轮切
                                    reasonofrdcut = 0;
                                }
                                // 轮切结果
                                if ((carr[64] >> k & 0x1) == 0 && (carr[64] >> k1 & 0x1) == 0) {
                                    // 不写入轮切结果
                                } else if ((carr[64] >> k & 0x1) == 1 && (carr[64] >> k1 & 0x1) == 0) {
                                    // 轮切成功
                                    resultofrdcut = 1;
                                } else {
                                    // 轮切失败
                                    resultofrdcut = 0;
                                }
                                // 后加速状态
                                if ((carr[75] >> k & 0x1) == 0 && (carr[75] >> k1 & 0x1) == 0) {
                                    // 不写入后加速状态
                                } else if ((carr[75] >> k & 0x1) == 1 && (carr[75] >> k1 & 0x1) == 0) {
                                    // 后加速开放
                                    statusofpacc = 1;
                                } else {
                                    // 后加速复位
                                    statusofpacc = 0;
                                }
                                // 后加速结果
                                if ((carr[76] >> k & 0x1) == 0 && (carr[76] >> k1 & 0x1) == 0) {
                                    // 不写入后加速结果
                                } else if ((carr[76] >> k & 0x1) == 1 && (carr[76] >> k1 & 0x1) == 0) {
                                    // 后加速成功
                                    resultofpacc = 1;
                                } else {
                                    // 后加速失败
                                    resultofpacc = 0;
                                }
                                int autoseljump = carr[81] >> (i - 1 + 4) & 0x1;
                                // 选线结果
                                if ((carr[82] >> k & 0x1) == 0 && (carr[82] >> k1 & 0x1) == 0) {
                                    // 不写入选线结果状态
                                } else if ((carr[82] >> k & 0x1) == 1 && (carr[82] >> k1 & 0x1) == 0) {
                                    // 选线成功
                                    resultofselln = 1;
                                } else {
                                    // 选线失败
                                    resultofselln = 0;
                                }

                                Scbussensor scbus = new Scbussensor();
                                scbus.setStationid(ad.getStationid());
                                scbus.setDevicegroup(ad.getDevicegroup());
                                scbus.setDeviceaddr((int) carr[9]);
                                scbus.setPointaddr(i);
                                Scbussensor record = scbusserviceimpl.getModel(scbus);
                                if (record == null) {
                                    setText("地址" + (int) carr[9] + "的母线监测点" + scbus.getPointaddr() + "不存在！请前往数据库添加");
                                    continue;
                                }
                                String alm = "";
                                scbus.setLastalarmlevel(0);
                                scbus.setLastalarmmessage("");
                                String phase = "";
                                String alarmcloumn = "";
                                alarmcloumn = "小电流选线" + scbus.getDeviceaddr() + "母线" + scbus.getPointaddr() + "A相"
                                        + "接地告警,";
                                if (aphasegrd == 1) {
                                    alm += alarmcloumn;
                                    scbus.setLastalarmlevel(2);
                                    scbus.setLastalarmmessage(alm);
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), alarmcloumn, true);
                                } else {
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), "", false);
                                }
                                alarmcloumn = "小电流选线" + scbus.getDeviceaddr() + "母线" + scbus.getPointaddr() + "B相"
                                        + "接地告警,";
                                if (bphasegrd == 1) {
                                    alm += alarmcloumn;
                                    scbus.setLastalarmlevel(2);
                                    scbus.setLastalarmmessage(alm);
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), alarmcloumn, true);
                                } else {
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), "", false);
                                }
                                alarmcloumn = "小电流选线" + scbus.getDeviceaddr() + "母线" + scbus.getPointaddr() + "C相"
                                        + "接地告警,";
                                if (cphasegrd == 1) {
                                    alm += alarmcloumn;
                                    scbus.setLastalarmlevel(2);
                                    scbus.setLastalarmmessage(alm);
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), alarmcloumn, true);
                                } else {
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), "", false);
                                }
                                alarmcloumn = "小电流选线" + scbus.getDeviceaddr() + "母线" + scbus.getPointaddr() + "谐振告警,";
                                if (resonantalm == 1) {
                                    alm += alarmcloumn;
                                    scbus.setLastalarmlevel(2);
                                    scbus.setLastalarmmessage(alm);
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), alarmcloumn, true);
                                } else {
                                    GetNormalAlarm(alarmcloumn, scbus.getDeviceaddr(), record.getDevicegroup(),
                                            scbus.getPointaddr(),
                                            record.getPointname(), "", false);
                                }

                                scbus.setLastgrdalm(grdalm);
                                scbus.setLastresonantalm(resonantalm);
                                scbus.setLastpicklnstart(picklnstart);
                                scbus.setLastbusbartwj(busbartwj);
                                scbus.setLastaphasegrd(aphasegrd);
                                scbus.setLastbphasegrd(bphasegrd);
                                scbus.setLastcphasegrd(cphasegrd);
                                scbus.setLastallreturn(allreturn);
                                scbus.setLastreasonofrdcut(reasonofrdcut);
                                scbus.setLastresultofrdcut(resultofrdcut);
                                scbus.setLaststatusofpacc(statusofpacc);
                                scbus.setLastresultofpacc(resultofpacc);
                                scbus.setLastautoseljump(autoseljump);
                                scbus.setLastresultofselln(resultofselln);
                                scbus.setLastbusbarovhl(busbarovhl);
                                scbus.setLastdatatime(dt);
                                scbus.setLastcommunicationstatus(0);
                                scbusserviceimpl.Update(scbus, false);
                            }
                            for (int j = 0; j < 6; j++) {
                                for (int i = 0; i < 8; i++) {
                                    Sclinesensor scline = new Sclinesensor();
                                    scline.setStationid(ad.getStationid());
                                    scline.setDevicegroup(ad.getDevicegroup());
                                    scline.setDeviceaddr((int) carr[9]);
                                    scline.setPointaddr(i + j * 8 + 1);
                                    Sclinesensor record = sclineserviceimpl.getModel(scline);
                                    if (record == null) {
                                        setText("地址" + (int) carr[9] + "的线路监测点" + scline.getPointaddr()
                                                + "不存在！请前往数据库添加");
                                        continue;
                                    }
                                    int offset = 0, grdalm = 0, tripfail = 0;
                                    if (j >= 4) {
                                        offset = 2;
                                    }
                                    grdalm = carr[19 + j + offset] >> i & 0x1;
                                    if (isnull(record.getLastgrdalm()) == 1) {
                                        grdalm = carr[19 + j] >> i & 0x1;
                                    }
                                    if (j == 0 || j == 1) {
                                        tripfail = carr[27 + j] >> i & 0x1;
                                    } else if (j == 2 || j == 3) {
                                        tripfail = carr[27 + j + 10] >> i & 0x1;
                                    } else if (j == 4 || j == 5) {
                                        tripfail = carr[27 + j + 20] >> i & 0x1;
                                    }
                                    int twj = carr[31 + j + offset] >> i & 0x1;
                                    int lntrip = carr[43 + j + offset] >> i & 0x1;
                                    int rdcuttrip = carr[55 + j + offset] >> i & 0x1;
                                    int pacctrip = carr[67 + j + offset] >> i & 0x1;
                                    String alm = "";
                                    scline.setLastalarmlevel(0);
                                    scline.setLastalarmmessage("");
                                    String alarmcloumn = "";
                                    alarmcloumn = "小电流选线" + scline.getDeviceaddr() + "线路" + scline.getPointaddr()
                                            + "接地告警,";
                                    if (grdalm == 1) {
                                        alm += alarmcloumn;
                                        scline.setLastalarmlevel(2);
                                        scline.setLastalarmmessage(alm);
                                        GetNormalAlarm(alarmcloumn, scline.getDeviceaddr(), record.getDevicegroup(),
                                                scline.getPointaddr(),
                                                record.getPointname(), alarmcloumn, true);
                                    } else {
                                        GetNormalAlarm(alarmcloumn, scline.getDeviceaddr(), record.getDevicegroup(),
                                                scline.getPointaddr(),
                                                record.getPointname(), "", false);
                                    }
                                    alarmcloumn = "小电流选线" + scline.getDeviceaddr() + "线路" + scline.getPointaddr()
                                            + "跳闸失败,";
                                    if (tripfail == 1) {
                                        alm += alarmcloumn;
                                        scline.setLastalarmlevel(2);
                                        scline.setLastalarmmessage(alm);
                                        GetNormalAlarm(alarmcloumn, scline.getDeviceaddr(), record.getDevicegroup(),
                                                scline.getPointaddr(),
                                                record.getPointname(), alarmcloumn, true);
                                    } else {
                                        GetNormalAlarm(alarmcloumn, scline.getDeviceaddr(), record.getDevicegroup(),
                                                scline.getPointaddr(),
                                                record.getPointname(), "", false);
                                    }

                                    scline.setLastgrdalm(grdalm);
                                    scline.setLasttripfail(tripfail);
                                    scline.setLasttwj(twj);
                                    scline.setLastlntrip(lntrip);
                                    scline.setLastrdcuttrip(rdcuttrip);
                                    scline.setLastpacctrip(pacctrip);
                                    scline.setLastdatatime(dt);
                                    scline.setLastcommunicationstatus(0);
                                    sclineserviceimpl.Update(scline, false);
                                }
                            }

                            int totalm = carr[79] >> 0 & 0x1;
                            int grdtotalm = carr[79] >> 1 & 0x1;
                            int triptotalm = carr[79] >> 2 & 0x1;
                            int resonanttotalm = carr[79] >> 3 & 0x1;
                            int deviceabnormalalm = carr[79] >> 4 & 0x1;
                            int recordcomplt = carr[79] >> 7 & 0x1;
                            int tripallowentry = carr[80] >> 0 & 0x1;
                            int paccallowentry = carr[80] >> 1 & 0x1;
                            int rdcutallowentry = carr[80] >> 2 & 0x1;
                            int inplaceoprtentry = carr[80] >> 3 & 0x1;
                            int servstausentry = carr[80] >> 4 & 0x1;
                            Scsensor sc = new Scsensor();
                            sc.setStationid(ad.getStationid());
                            sc.setDevicegroup(ad.getDevicegroup());
                            sc.setDeviceaddr((int) carr[9]);
                            sc.setPointaddr(1);
                            Scsensor record = scserviceimpl.getModel(sc);
                            if (record == null) {
                                setText("地址" + (int) carr[9] + "的母线监测点" + 1 + "不存在！请前往数据库添加");
                                setText("================遥信解析完毕================");
                                return;
                            }
                            sc.setLasttotalm(totalm);
                            sc.setLastgrdtotalm(grdtotalm);
                            sc.setLasttriptotalm(triptotalm);
                            sc.setLastresonanttotalm(resonanttotalm);
                            sc.setLastdeviceabnormalalm(deviceabnormalalm);
                            sc.setLastrecordcomplt(recordcomplt);
                            sc.setLasttripallowentry(tripallowentry);
                            sc.setLastpaccallowentry(paccallowentry);
                            sc.setLastrdcutallowentry(rdcutallowentry);
                            sc.setLastinplaceoprtentry(inplaceoprtentry);
                            sc.setLastservstausentry(servstausentry);
                            sc.setLastdatatime(dt);
                            sc.setLastcommunicationstatus(0);
                            scserviceimpl.Update(sc, false);
                            setText("================遥信解析完毕================");
                        }
                        telecommandTime = System.currentTimeMillis() + expirationTime;
                    } else {
                        return;
                    }
                }
            } else {
                return;
            }
        } else if ("61".equals(buffer.substring(14, 16))) {
            if (System.currentTimeMillis() > telemetryTime) {
                synchronized (telemetryState) {
                    if (System.currentTimeMillis() > telemetryTime) {
                        byte[] carr = HexUtil.hexString2Bytes(buffer);
                        if (carr[7] == 0x61)// yaoce
                        {
                            setText("==============正在解析遥测数据==============");
                            for (int i = 1; i <= 4; i++) {
                                float Lastaphasevolt = (short) (((carr[(i - 1) * 3 * 6 + 14] & 0x00FF) << 8)
                                        | (0x00FF & carr[(i - 1) * 3 * 6 + 13])) / 100f;
                                float Lastbphasevolt = (short) (((carr[(i - 1) * 3 * 6 + 16] & 0x00FF) << 8)
                                        | (0x00FF & carr[(i - 1) * 3 * 6 + 15])) / 100f;
                                float Lastcphasevolt = (short) (((carr[(i - 1) * 3 * 6 + 20] & 0x00FF) << 8)
                                        | (0x00FF & carr[(i - 1) * 3 * 6 + 19])) / 100f;
                                float Lastzordervoltone = (short) (((carr[(i - 1) * 3 * 6 + 22] & 0x00FF) << 8)
                                        | (0x00FF & carr[(i - 1) * 3 * 6 + 21])) / 100f;
                                float Lastzordervolttwo = (short) (((carr[(i - 1) * 3 * 6 + 26] & 0x00FF) << 8)
                                        | (0x00FF & carr[(i - 1) * 3 * 6 + 25])) / 100f;
                                Scbussensor scbus = new Scbussensor();
                                scbus.setStationid(ad.getStationid());
                                scbus.setDevicegroup(ad.getDevicegroup());
                                scbus.setDeviceaddr((int) carr[9]);
                                scbus.setPointaddr(i);
                                Scbussensor record = scbusserviceimpl.getModel(scbus);
                                if (record == null) {
                                    setText("地址" + (int) carr[9] + "的母线监测点" + scbus.getPointaddr() + "不存在！请前往数据库添加");
                                    continue;
                                }
                                scbus.setLastaphasevolt(Lastaphasevolt);
                                scbus.setLastbphasevolt(Lastbphasevolt);
                                scbus.setLastcphasevolt(Lastcphasevolt);
                                scbus.setLastzordervoltone(Lastzordervoltone);
                                scbus.setLastzordervolttwo(Lastzordervolttwo);
                                scbus.setLastdatatime(dt);
                                scbus.setLasthisdatatime(addHistory(record));
                                scbus.setLastcommunicationstatus(0);
                                scbusserviceimpl.Update(scbus, false);
                            }
                            for (int i = 1; i <= 24; i++) {
                                {
                                    float zordercurr = (short) (((carr[92 + (i - 1) * 6] & 0x00FF) << 8)
                                            | (0x00FF & carr[91 + (i - 1) * 6])) / 100f;
                                    Sclinesensor scline = new Sclinesensor();
                                    scline.setStationid(ad.getStationid());
                                    scline.setDevicegroup(ad.getDevicegroup());
                                    scline.setDeviceaddr((int) carr[9]);
                                    scline.setPointaddr(2 * i - 1);
                                    Sclinesensor record = sclineserviceimpl.getModel(scline);
                                    if (record == null) {
                                        setText("地址" + (int) carr[9] + "的线路监测点" + scline.getPointaddr()
                                                + "不存在！请前往数据库添加");
                                        continue;
                                    }
                                    scline.setLastzordercurr(zordercurr);
                                    scline.setLastdatatime(dt);
                                    scline.setLasthisdatatime(addHistory(record));
                                    scline.setLastcommunicationstatus(0);
                                    sclineserviceimpl.Update(scline, false);
                                }

                                {
                                    float zordercurr = (short) (((carr[94 + (i - 1) * 6] & 0x00FF) << 8)
                                            | (0x00FF & carr[93 + (i - 1) * 6])) / 100f;
                                    Sclinesensor scline = new Sclinesensor();
                                    scline.setStationid(ad.getStationid());
                                    scline.setDevicegroup(ad.getDevicegroup());
                                    scline.setDeviceaddr((int) carr[9]);
                                    scline.setPointaddr(2 * i);
                                    Sclinesensor record = sclineserviceimpl.getModel(scline);
                                    if (record == null) {
                                        setText("地址" + (int) carr[9] + "的线路监测点" + scline.getPointaddr()
                                                + "不存在！请前往数据库添加");
                                        continue;
                                    }
                                    scline.setLastzordercurr(zordercurr);
                                    scline.setLastdatatime(dt);
                                    scline.setLasthisdatatime(addHistory(record));
                                    scline.setLastcommunicationstatus(0);
                                    sclineserviceimpl.Update(scline, false);
                                }
                            }
                            int currvaluearea = (int) (((carr[1] & 0x00FF) << 8) | (0x00FF & carr[1]));
                            int fatrecdsernum = (int) (((carr[1] & 0x00FF) << 8) | (0x00FF & carr[1]));
                            String versionnum = "";
                            Scsensor sc = new Scsensor();
                            sc.setStationid(ad.getStationid());
                            sc.setDevicegroup(ad.getDevicegroup());
                            sc.setDeviceaddr((int) carr[9]);
                            sc.setPointaddr(1);
                            Scsensor record = scserviceimpl.getModel(sc);
                            if (record == null) {
                                setText("地址" + (int) carr[9] + "的母线监测点" + sc.getPointaddr() + "不存在！请前往数据库添加");
                                setText("================遥测解析完毕================");
                                return;
                            }
                            sc.setLastcurrvaluearea(currvaluearea);
                            sc.setLastfatrecdsernum(fatrecdsernum);
                            sc.setLastversionnum(versionnum);
                            sc.setLastdatatime(dt);
                            sc.setLasthisdatatime(addHistory(record));
                            sc.setLastcommunicationstatus(0);
                            scserviceimpl.Update(sc, false);
                            setText("================遥测解析完毕================");
                        }
                        // 两秒计算一次
                        telemetryTime = System.currentTimeMillis() + expirationTime;
                    } else {
                        return;
                    }
                }
            } else {
                return;
            }
        }
    }

    private Date addHistory(Scsensor sensor) { // sc
        sensor = scserviceimpl.getModel(sensor);
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Scsensor sensor) {
        Schistory schis = new Schistory();
        schis.setStationid(sensor.getStationid());
        schis.setDevicegroup(sensor.getDevicegroup());
        schis.setPointaddr(sensor.getPointaddr());
        schis.setDeviceaddr(sensor.getDeviceaddr());
        schis.setPointname(sensor.getPointname());
        schis.setAddrname(sensor.getAddrname());
        schis.setTotalm(sensor.getLasttotalm());
        schis.setGrdtotalm(sensor.getLastgrdtotalm());
        schis.setTriptotalm(sensor.getLasttriptotalm());
        schis.setResonanttotalm(sensor.getLastresonanttotalm());
        schis.setDeviceabnormalalm(sensor.getLastdeviceabnormalalm());
        schis.setRecordcomplt(sensor.getLastrecordcomplt());
        schis.setTripallowentry(sensor.getLasttripallowentry());
        schis.setPaccallowentry(sensor.getLastpaccallowentry());
        schis.setRdcutallowentry(sensor.getLastrdcutallowentry());
        schis.setInplaceoprtentry(sensor.getLastinplaceoprtentry());
        schis.setServstausentry(sensor.getLastservstausentry());
        schis.setDatatime(sensor.getLastdatatime());
        schis.setCurrvaluearea(sensor.getLastcurrvaluearea());
        schis.setFatrecdsernum(sensor.getLastfatrecdsernum());
        scserviceimpl.Add(schis);
    }

    private Date addHistory(Scbussensor sensor) { // scbus
        sensor = scbusserviceimpl.getModel(sensor);
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Scbussensor sensor) {
        Scbushistory scbushis = new Scbushistory();
        scbushis.setDeviceaddr(sensor.getDeviceaddr());
        scbushis.setStationid(sensor.getStationid());
        scbushis.setDevicegroup(sensor.getDevicegroup());
        scbushis.setPointaddr(sensor.getPointaddr());
        scbushis.setPointname(sensor.getPointname());
        scbushis.setGrdalm(sensor.getLastgrdalm());
        scbushis.setResonantalm(sensor.getLastresonantalm());
        scbushis.setPicklnstart(sensor.getLastpicklnstart());
        scbushis.setBusbartwj(sensor.getLastbusbartwj());
        scbushis.setAphasegrd(sensor.getLastaphasegrd());
        scbushis.setBphasegrd(sensor.getLastbphasegrd());
        scbushis.setCphasegrd(sensor.getLastcphasegrd());
        scbushis.setAllreturn(sensor.getLastallreturn());
        scbushis.setReasonofrdcut(sensor.getLastreasonofrdcut());
        scbushis.setResultofrdcut(sensor.getLastresultofrdcut());
        scbushis.setStatusofpacc(sensor.getLaststatusofpacc());
        scbushis.setResultofpacc(sensor.getLastresultofpacc());
        scbushis.setResultofselln(sensor.getLastresultofselln());
        scbushis.setBusbarovhl(sensor.getLastbusbarovhl());
        scbushis.setDatatime(sensor.getLastdatatime());
        scbushis.setAphasevolt(sensor.getLastaphasevolt());
        scbushis.setBphasevolt(sensor.getLastbphasevolt());
        scbushis.setCphasevolt(sensor.getLastcphasevolt());
        scbushis.setZordervoltone(sensor.getLastzordervoltone());
        scbushis.setZordervolttwo(sensor.getLastzordervolttwo());
        scbusserviceimpl.Add(scbushis);
    }

    private Date addHistory(Sclinesensor sensor) {
        sensor = sclineserviceimpl.getModel(sensor);
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Sclinesensor sensor) {
        Sclinehistory sclinehis = new Sclinehistory();
        sclinehis.setTripfail(sensor.getLasttripfail());
        sclinehis.setTwj(sensor.getLasttwj());
        sclinehis.setGrdalm(sensor.getLastgrdalm());
        sclinehis.setLntrip(sensor.getLastlntrip());
        sclinehis.setRdcuttrip(sensor.getLastrdcuttrip());
        sclinehis.setPacctrip(sensor.getLastpacctrip());
        sclinehis.setDatatime(sensor.getLastdatatime());
        sclinehis.setPointname(sensor.getPointname());
        sclinehis.setPointaddr(sensor.getPointaddr());
        sclinehis.setDeviceaddr(sensor.getDeviceaddr());
        sclinehis.setDevicegroup(sensor.getDevicegroup());
        sclinehis.setStationid(sensor.getStationid());
        sclinehis.setZordercurr(sensor.getLastzordercurr());
        sclineserviceimpl.Add(sclinehis);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        issend.put(Thread.currentThread().getId(), true);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if ((new Date().getTime() - lastrecvtime) > 10000) {
                sclineserviceimpl.UpdateStatus(ad, null, 1);
                scbusserviceimpl.UpdateStatus(ad, null, 1);
                scserviceimpl.UpdateStatus(ad, null, 1);
            }
            Thread.sleep(1000);
        }
    }
}
